﻿Imports System.IO
Imports MeoTom.Core.BLL
Imports MeoTom.Core

Namespace Control

    Partial Public Class ArticleEdit
        Inherits UserControl

        Public ObjCategory As New Categories()
        Public ObjArticle As New Articles()
        Public ObjTag As New Tags()
        Public Util2 As New Utilities.Common()
        Public StrCatTemp As String = ""

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            Select Case Request.QueryString("MsgID")
                Case "2"
                    lblError.Attributes.Remove("style")
                    lblError.InnerHtml = "Post updated." '<a target=""_blank"" href=""" & Configs.HomeUrl & "Preview/Article/?ID=" & Request.QueryString("ID") & """ title=""View Post"">View post</a>"
                Case "4"
                    lblError.Attributes.Remove("style")
                    lblError.InnerHtml = "Post updated."
                Case "6"
                    lblError.Attributes.Remove("style")
                    lblError.InnerHtml = "Post published." '<a target=""_blank"" href=""" & Configs.HomeUrl & "Published/Article/?ID=" & Request.QueryString("ID") & """ title=""View post"">View post</a>"
                Case "7"
                    lblError.Attributes.Remove("style")
                    lblError.InnerHtml = "Post saved."
            End Select

            If Not IsPostBack Then
                Dim previousPage As String = ""
                If Request.QueryString.ToString = vbNullString Then
                    previousPage = Server.UrlEncode(Request.ServerVariables("PATH_INFO"))
                Else
                    previousPage = Server.UrlEncode(Request.ServerVariables("PATH_INFO") & "?" & Request.QueryString.ToString())
                End If
                Util2.ValidateLogin(previousPage)

                If Not Request.QueryString("ID") = vbNullString Then
                    LoadArticle(Integer.Parse(Request.QueryString("ID")))
                    GetTag()
                    catdetail.InnerHtml = ObjCategory.WriteCategoryInside(3, ObjArticle.GetAllCat(1))
                    ArticlePublishContent.InnerHtml = WriteScheduleDate()
                    ArticleVisibleContent.InnerHtml = WriteVisibilityInf()
                End If
            End If
        End Sub

        Public Function WriteScheduleDate() As String
            Dim strOut As New StringBuilder()
            strOut.Append("<br /><select name=""mmmm"" id=""mmmm""><option value=""1"">Jan</option><option value=""2"">Feb</option><option value=""3"">Mar</option><option value=""4"">Apr</option><option value=""5"">May</option><option value=""6"">Jun</option><option value=""7"">Jul</option><option value=""8"">Aug</option><option value=""9"">Sep</option><option value=""10"">Oct</option><option value=""11"">Nov</option><option value=""12"">Dec</option></select> ")
            strOut.Append("<input type=""text"" style=""width:auto;"" id=""dd"" name=""dd"" value=""").Append(Day(objArticle.ReleaseDate)).Append(""" size=""2"" maxlength=""2"" autocomplete=""off"" />")
            strOut.Append(", <input type=""text"" style=""width:auto;"" id=""yy"" name=""yy"" value=""").Append(Year(objArticle.ReleaseDate)).Append(""" size=""4"" maxlength=""4"" tabindex=""4"" autocomplete=""off"" /> @ <input style=""width:auto;"" type=""text"" id=""hh"" name=""hh"" value=""").Append(Hour(objArticle.ReleaseDate)).Append(""" size=""2"" maxlength=""2"" tabindex=""4"" autocomplete=""off"" /> : <input style=""width:auto;"" type=""text"" id=""mn"" name=""mn"" value=""").Append(Minute(objArticle.ReleaseDate)).Append(""" size=""2"" maxlength=""2"" tabindex=""4"" autocomplete=""off"" /><input type=""hidden"" id=""ss"" name=""ss"" value=""").Append(Second(objArticle.ReleaseDate)).Append(""" />")
            strOut.Append("<input type=""button"" value=""OK"" class=""button"" onclick=""javascript:Util.PublishConfirmAction();"" /> ")
            strOut.Append("<a onclick=""javascript:Util.CancelArticlePublish();"" title=""Cancel"" href=""javascript:void(0);"">Cancel</a><input type=""hidden"" id=""txtReleaseDate"" value=""").Append(objArticle.ReleaseDate).Append(""" name=""txtReleaseDate"" />")
            strOut.Append("<script type=""text/javascript"" language=""javascript"">gmobj(""mmmm"").value = ").Append(Month(objArticle.ReleaseDate)).Append(";</script>")
            Return strOut.ToString()
        End Function

        Public Function WriteVisibilityInf()
            Dim strCheck0 As String = " checked=""checked"" "
            Dim strCheck1 As String = " checked=""checked"" "
            Dim strCheck2 As String = " checked=""checked"" "
            If objArticle.PostVisible = "0" Then
                strCheck1 = ""
                strCheck2 = ""
            ElseIf objArticle.PostVisible = "1" Then
                strCheck0 = ""
                strCheck2 = ""
            ElseIf objArticle.PostVisible = "2" Then
                strCheck0 = ""
                strCheck1 = ""
            End If
            Dim strOut As New StringBuilder()
            strOut.Append("<br /><label><input type=""radio""").Append(strCheck0).Append("name=""cboVisible"" id=""txtArticlePublic"" value=""0"" onclick=""javascript:Util.ArticlePublic();"" />Public</label><br />")
            strOut.Append("<label><input type=""radio""").Append(strCheck1).Append("name=""cboVisible"" id=""txtArticlePassword"" value=""1"" onclick=""javascript:Util.ArticlePassword();"" />Password protected</label><br />")
            strOut.Append("<span id=""frmArticlePwd"" style=""font-size:11px;display:none;""><label>Password<br /><input type=""text"" id=""txtArticlePwd"" name=""txtArticlePwd"" /></label><br /></span>")
            strOut.Append("<label><input type=""radio""").Append(strCheck2).Append("name=""cboVisible"" id=""txtArticlePrivate"" value=""2"" onclick=""javascript:Util.ArticlePrivate();"" />Private</label><br />")
            strOut.Append("<input type=""button"" class=""button"" value=""OK"" onclick=""javascript:Util.ConfirmAction('").Append(ArticleVisibleContent.ClientID).Append("');"" />&nbsp;&nbsp;<a href=""javascript:void(0);"" title=""Cancel"" onclick=""javascript:Util.CancelArticleVisible('").Append(ArticleVisibleContent.ClientID).Append("');"">Cancel</a>")
            strOut.Append("<input type=""hidden"" name=""txtPostVisible"" id=""txtPostVisible"" value=""").Append(objArticle.PostVisible).Append(""" />")
            strOut.Append("<input type=""hidden"" name=""txtArticlePath"" id=""txtArticlePath"" value=""").Append(objArticle.ArticlePath).Append(""" />")
            strOut.Append("<input type=""hidden"" name=""txtCreateDate"" id=""txtCreateDate"" value=""").Append(objArticle.CreatedDate.ToString()).Append(""" />")
            Return strOut.ToString()
        End Function

        Public Sub LoadArticle(ByVal id As Integer)
            objArticle.ArticlesID = id
            objTag.ArticleID = id
            objArticle.GetByEdit()

            Select Case objArticle.PostVisible
                Case "0"
                    lblArticleVisiblity.Text = "Public"
                Case "1"
                    lblArticleVisiblity.Text = "Password protected"
                Case "2"
                    lblArticleVisiblity.Text = "Private"
            End Select

            If objArticle.Approved Then
                lblStatus.InnerHtml = "Status: <b>Published</b>"
                btnUpdate.Text = "Update Post"
                btnSave.Visible = False
            Else
                lblStatus.InnerHtml = "Status: <b>Draft</b>"
                btnUpdate.Style.Add("width", "30%")
            End If

            If objArticle.ImagePath = "" Then
                imgPreView.ImageUrl = "/images/no_image_s.gif"
            Else
                imgPreView.ImageUrl = "/Uploads/" & objArticle.ImagePath
                imgPreView.Width = "250"
                'imgPreView.Height = "130"
            End If

            txtImagePath.Value = objArticle.ImagePath
            txtBody.Value = Server.HtmlDecode(objArticle.Body)
            txtTitle.Text = Server.HtmlDecode(objArticle.Title.Trim)
            txtTitleNone.Value = objArticle.TitleNone
            txtDesc.Text = objArticle.Abstract
            drpCommentEnabled.Checked = objArticle.CommentEnabled
            drpIsMedia.Checked = objArticle.IsMedia
            drpIsPicture.Checked = objArticle.IsPicture
            drpIsTopPage.Checked = objArticle.IsTopPage
            drpIsVote.Checked = objArticle.IsVote
            txtTag.Text = objTag.GetTagByArticleEdit()
        End Sub

        Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
            Dim strArticleID As String = ""
            Dim d As DateTime
            If txtTitle.Text = vbNullString Then
                txtTitle.Text = "No Title"
            ElseIf txtTitle.Text.Length > 550 Then
                txtTitle.Text = Server.HtmlEncode(Left(txtTitle.Text.Trim, 500))
            End If
            objArticle.Approved = True
            ArticleInfo()
            d = DateTime.Parse(Request.Form("txtCreateDate").ToString())
            strArticleID = objArticle.ArticlesId.ToString()

            objArticle.WriteXmlbyID(objArticle.ArticlesId, d.Day, d.Month, d.Year, objArticle.Body, objArticle.CategoryId, strCatTemp)
            objArticle.WriteRss(1000000)
            objArticle.WriteTop10Last()
            objArticle.WriteTop10View()
            objArticle.WriteTopStory()

            'Get Default Tag
            objTag.GetDefaultTag(0)

            Response.Redirect("/mt-inside/ArticleUpdate.aspx?action=Edit&ID=" & strArticleID & "&MsgID=2")
        End Sub

        Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
            Dim strArticleID As String = ""
            Dim d As DateTime

            If txtTitle.Text = vbNullString Then
                txtTitle.Text = "No Title"
            ElseIf txtTitle.Text.Length > 550 Then
                txtTitle.Text = Server.HtmlEncode(Left(txtTitle.Text.Trim, 500))
            End If

            If objArticle.Approved Then
                objArticle.Approved = True
            Else
                objArticle.Approved = False
            End If

            ArticleInfo()
            d = DateTime.Parse(Request.Form("txtCreateDate").ToString())
            strArticleID = objArticle.ArticlesId.ToString()

            objArticle.WriteXmlbyID(objArticle.ArticlesId, d.Day, d.Month, d.Year, objArticle.Body, objArticle.CategoryId, strCatTemp)

            objArticle.WriteTopStory()
            objTag.GetDefaultTag(0)
            Response.Redirect("/mt-inside/ArticleUpdate.aspx?action=Edit&ID=" & strArticleID & "&MsgID=7")
        End Sub

        Public Sub ArticleInfo()
            Dim fileName As String = objArticle.Util.DateTimeToNum()
            objArticle.ArticlesId = Integer.Parse(Request.QueryString("ID"))
            objArticle.Title = util2.NoHTML(Server.HtmlEncode(txtTitle.Text.Trim))
            objArticle.Body = txtBody.Value
            objArticle.Abstract = Regex.Replace(objArticle.Body, "\t|\r|\n", "")

            'Dim MatchFLVPlayer As Match = Regex.Match(objArticle.Abstract, "<div (?<StringRemove0>.*?)divRemoveMediaPlayer(?<StringRemove0>.*?)>(?<StringRemove1>.*?)</tbody></table></div>")
            'While MatchFLVPlayer.Success
            '    objArticle.Abstract = objArticle.Abstract.Replace(MatchFLVPlayer.Groups("StringRemove1").Value, "")
            '    MatchFLVPlayer = MatchFLVPlayer.NextMatch
            'End While
            'MatchFLVPlayer = Nothing

            'Dim MatchCode As Match = Regex.Match(objArticle.Abstract, "<pre (?<StringRemove0>.*?)code(?<StringRemove2>.*?)>(?<StringRemove1>.*?)</pre>")
            'While MatchCode.Success
            '    objArticle.Abstract = objArticle.Abstract.Replace(MatchCode.Groups("StringRemove1").Value, "")
            '    MatchCode = MatchCode.NextMatch
            'End While
            'MatchCode = Nothing

            'Dim MatchHyperLink As Match = Regex.Match(objArticle.Abstract, "\b([\d\w\.\/\+\-\?\:]*)((ht|f)tp(s|)\:\/\/|[\d\d\d|\d\d]\.[\d\d\d|\d\d]\.|www\.|\.tv|\.ac|\.com|\.edu|\.gov|\.int|\.mil|\.net|\.org|\.biz|\.info|\.name|\.pro|\.museum|\.co)([\d\w\.\/\%\+\-\=\&amp;\?\:\\\&quot;\'\,\|\~\;]*)\b")
            'While MatchHyperLink.Success
            '    objArticle.Abstract = objArticle.Abstract.Replace(MatchHyperLink.Value, "")
            '    MatchHyperLink = MatchHyperLink.NextMatch
            'End While
            'MatchHyperLink = Nothing

            Dim strUserName As String = ""
            If util2.GetCookie("UserID") = vbNullString Then
                objArticle.UserID = Integer.Parse(util2.GetSession("UserID"))
                strUserName = util2.GetSession("UserName")
            Else
                objArticle.UserID = Integer.Parse(util2.GetCookie("UserID"))
                strUserName = util2.GetCookie("UserName")
            End If

            objArticle.Abstract = Left(util2.NoHTML(txtDesc.Text), 250)
            objArticle.IsMedia = drpIsMedia.Checked
            objArticle.IsPicture = drpIsPicture.Checked
            objArticle.IsTopPage = drpIsTopPage.Checked
            objArticle.IsVote = drpIsVote.Checked
            objArticle.CommentEnabled = drpCommentEnabled.Checked
            objArticle.ExpireDate = DateTime.Now.AddYears(1000)
            objArticle.PostVisible = Integer.Parse(Request.Form("txtPostVisible").ToString())
            objArticle.TitleNone = txtTitleNone.Value
            objArticle.ArticlePath = Request.Form.Get("txtArticlePath")

            If fileUpload.HasFile Then
                Dim RandomStr As New Core.Utilities.RandomStrings
                Dim strFileName As String = RandomStr.GenerateRandomString(DateTime.Now) & ".jpg"
                Dim strFolder As String = Configs.UserFolder & strUserName & "\" & DateTime.Now.Year.ToString & "\" & Right("0" & DateTime.Now.Month.ToString, 2) & "\" & Right("0" & DateTime.Now.Day.ToString, 2) & "\"
                If Not Directory.Exists(strFolder) Then
                    Directory.CreateDirectory(strFolder)
                End If

                Dim objImage As New Core.Utilities.ImageUtil(fileUpload.PostedFile.InputStream, 1024, 1024, "UploadService", strUserName, strFileName)
                objImage.PublicUpload(228, 0, strFileName, "")

                objArticle.ImagePath = strFolder.Replace(Configs.UserFolder, "").Replace("\", "/") & "228x0__" & strFileName
            Else
                objArticle.ImagePath = txtImagePath.Value
            End If

            If Not Request.Form.Get("txtArticlePwd") = vbNullString Then
                objArticle.ArticlePassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Request.Form("txtArticlePwd").ToString(), "MD5")
            End If

            If Not Request.Form("txtReleaseDate").ToString() = vbNullString Then
                objArticle.ReleaseDate = DateTime.Parse(Request.Form("txtReleaseDate").ToString())
            End If

            'Update Article
            objArticle.Update()
            'Remove Old Article Cat
            objArticle.RemoveTempArticleCat()

            'Create Category
            If Request.Form.Get("cboCategory") = vbNullString Then
                objArticle.CategoryId = 1
                objArticle.SetTempArticleCat(1)
            Else
                For Each strCatID As String In Regex.Split(Request.Form.Get("cboCategory"), ",")
                    strCatTemp = strCatID

                    Dim str() As String = strCatTemp.Split(New Char() {"|"c})
                    objArticle.CategoryId = Integer.Parse(str(0))
                    objArticle.SetTempArticleCat(1)
                Next
            End If

            'Create New Tag
            CreateTag(txtTag.Text, objArticle.ArticlesId)
        End Sub

        Public Sub GetTag()
            tags.InnerHtml = objTag.GetTagByArticleUpdate(txtTag.ClientID)
        End Sub

        Public Sub CreateTag(ByVal tagname As String, ByVal ArticleID As Integer)
            If Not tagname = vbNullString Then
                For Each Str As String In Regex.Split(tagname, ",")
                    If Not Str.Trim = "" Then
                        objTag.TagName = Str.Trim
                        objTag.ArticleID = ArticleID
                        objTag.Create()
                    End If
                Next
            End If
        End Sub

        Private Sub lnkDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkDelete.Click
            Dim objComment As New Global.MeoTom.Core.BLL.Comments()
            objArticle.ArticlesID = Integer.Parse(Request.QueryString("ID"))
            objArticle.GetByID()
            objTag.ArticleID = objArticle.ArticlesID
            objTag.UpdateTotalArticle()

            util2.DeleteFile(Configs.ArticleFile & "ListFile\" & objArticle.CreatedDate.Year.ToString() & "\" & objArticle.CreatedDate.Month.ToString() & "\" & objArticle.CreatedDate.Day.ToString() & "\" & objArticle.ArticlesID & ".xml")

            objComment.ArticleId = Integer.Parse(Request.QueryString("ID"))
            objComment.DeleteByArticle()

            objArticle.Delete()
            objArticle.WriteTopStory()
            objArticle.WriteTop10View()
            objArticle.WriteTop10Last()
            objTag.GetDefaultTag(0)

            objComment = Nothing

            Response.Redirect("/mt-inside/ArticleUpdate.aspx", False)
        End Sub
    End Class
End Namespace